package com.aloha.auth.support.impl;

import com.aloha.auth.annotation.CheckPermission;
import com.aloha.auth.exception.AuthException;
import com.aloha.auth.support.AuthUtils;
import com.aloha.auth.support.AuthValidator;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 注解权限校验
 *
 * @author zhdai
 * @date 2023/11/10 14:16
 */
public class AnnoAuthValidator implements AuthValidator {

    @Override
    public boolean validate(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {
        // 先校验type
        CheckPermission permission = handler.getBeanType().getAnnotation(CheckPermission.class);
        List<String> needPerms;
        if (permission != null) {
            needPerms = Arrays.stream(permission.value()).collect(Collectors.toList());
            if (!AuthUtils.check(permission.mode(), needPerms)) {
                throw new AuthException(401, "没有权限");
            }
        }
        // 再校验Method
        permission = handler.getMethodAnnotation(CheckPermission.class);
        if (permission != null) {
            needPerms = Arrays.stream(permission.value()).collect(Collectors.toList());
            if (AuthUtils.check(permission.mode(), needPerms)) {
                return true;
            }
            throw new AuthException(401, "没有权限");
        }
        return true;
    }
}
